<?php


namespace app\common\model;


use app\common\validate\ConfigValidate;
use think\facade\Db;
use think\Exception;

class Config extends BaseModel
{
    /**
     * 获取单个配置
     * @Author zengxin(573908667@qq.com)
     * @param $key
     * @param false $force
     * @return mixed
     */
    public static function getOne($key,$force = false)
    {
        $redis = redis_instance();
        $key   = REDIS_KEY . ":config";
        if($force) {
            $res   = $redis->exists($key);
            if ($res) {
                $data = $redis->get($key);
                $data = json_decode($data, true);
            } else {
                $data = self::column('value', 'key');
                $redis->set($key, json_encode($data));
            }
        }else{
            $data = self::column('value', 'key');
            $redis->set($key, json_encode($data));
        }
        return $data[$key];
    }

    /**
     * 获取全部配置
     * @Author zengxin(573908667@qq.com)
     * @param false $force
     * @return array|mixed
     */
    public static function getAll($force = false)
    {
        $redis = redis_instance();
        $key   = REDIS_KEY . ":config";
        if($force){
            $res   = $redis->exists($key);
            if ($res) {
                return json_decode($redis->get($key),true);
            }else{
                $data = self::column('value', 'key');
                $redis->set($key, json_encode($data));
                return $data;
            }
        }else{
            $data = self::column('value', 'key');
            $redis->set($key, json_encode($data));
            return $data;
        }
    }

    /**
     * 保存数据
     * @Author zengxin(573908667@qq.com)
     * @param $data
     * @return bool
     */
    public static function saveData($data)
    {
        $validate = new ConfigValidate();
        $redis = redis_instance();
        $key   = REDIS_KEY . ":config";
        Db::startTrans();
        try{
            foreach ($data as $key=>$value){
                $model = self::where('key',$key)->find();
                if($model){
                    $model->save(['value'=>htmlspecialchars_decode($value)]);
                }else{
                    self::create([
                        'key' => $key,
                        'value' => htmlspecialchars_decode($value),
                        'comment' => $validate->getComment($key)
                    ]);
                }
            }
            $data = self::column('value', 'key');
            $redis->set($key, json_encode($data));
            Db::commit();
            return true;
        }catch (Exception $e){
            Db::rollback();
            json_response(0,$e->getMessage());
        }

    }
}